package com.ag.answergames.controller;

import cn.hutool.http.HttpUtil;

import com.ag.answergames.service.user.UserService;
import com.ag.answergames.util.Tools;
import com.ag.answergames.vo.UserVO;
import com.ag.answergames.vo.common.Result;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


@RestController
@RequestMapping("/back")
@Api
public class UserController {

    @Qualifier("userServiceImpl")
    @Autowired
    UserService userService;

    /**
     * 用户注册
     * @param phone 微信用户的手机号
     * @param code  解析出openId
     * @return
     *
     * userId
     * openId
     *
     */
//    @PostMapping("/user/register")
//    public Result<UserVO> userRegister(@RequestParam("phone") String phone,@RequestParam("verifyCode") String verifyCode,@RequestParam("code") String code){
//
//        return userService.userRegister (phone,verifyCode,code);
//
//    }

    @RequestMapping("/user/register")
    @ApiOperation(value = "获取用户在小程序的openId", notes="小程序客户端通过wx.login函数获取用户的code。（code的本质是包含用户openid的加密字符串）然后，把code发给接口函数，接口函数通过应用的SECRETKEY解密，得到用户的openid。openId是用户的唯一身份识别。", response = Result.class, httpMethod = "GET")
    public Result userRegister(
            @ApiParam(value = "包含用户openId的加密字符串", required = true)
            @RequestParam String code,@RequestParam String verifyCode,@RequestParam String phone) {

        try
        {
//            if (Tools.IsNullOrEmpty(code)) {
//                return Result.GetFailResMsg("参数错误").ToJson();
//            }

            //1.得到解密code的网址
            /**
             * https://api.weixin.qq.com/sns/oauth2/access_token接口得到的返回值为：
             *{
             *   "access_token": "",
             *   "expires_in": 7200,
             *   "refresh_token": "",
             *   "openid": "",
             *   "scope": ""
             * }
             *
             * https://api.weixin.qq.com/sns/jscode2session接口得到的返回值为：
             * {
             *   "session_key": "",
             *   "expires_in": 7200,
             *   "openid": "",
             *   "unionid": ""
             * }
             *
             */
            String getTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                    "appid=" + "wx2687e5d495023188" +
                    "&secret=" + "86ec9514fc22c5b1651a5f69fadd9eb1" +
                    "&code=" + code +
                    "&grant_type=authorization_code";
            /*String getTokenUrl = "https://api.weixin.qq.com/sns/jscode2session?" +
                    "appid=" + "wx2687e5d495023188"
                    + "&secret=" + "86ec9514fc22c5b1651a5f69fadd9eb1"
                    + "&js_code=" + code
                    + "&grant_type=authorization_code";*/

            //2.获取解密的json
            //这个属于发起请求并获取json数据（得引入hutool，即上面引入的第二个依赖）
            String json= HttpUtil.createGet(getTokenUrl).execute().body();

//            //3.解析json
//            JSONObject jsonObject = JSONObject.parseObject(json);
//            String openId = jsonObject.getString("openid");
//            String sessionKey = jsonObject.getString("session_key");
//            String expiresIn = jsonObject.getString("expires_in");

//            if(Tools.IsNullOrEmpty(openId) ||
//                    Tools.IsNullOrEmpty(sessionKey) ||
//                    Tools.IsNullOrEmpty(expiresIn)){
//                return ResMsg.GetFailResMsg("处理失败").ToJson();
//            }


            Result<UserVO> userVOResult = userService.userRegister (code, verifyCode, phone);

            return Result.success (userVOResult);
        }
        catch(Exception ex) {
            System.out.println(ex.getMessage());
            return Result.failed ();
        }
    }




    /**
     * 编辑用户信息
     * @param userVO
     * @return
     */
    @PostMapping("/user/info/edit")
    public Result<Integer> userEdit(UserVO userVO){

        return userService.userEdit (userVO);

    }

    /**
     * 获取用户信息
     * @return
     */
    @PostMapping("user/info")
    public Result<UserVO> userInfo(@RequestParam("openId")String openId){

        return userService.userInfo (openId);


    }


}
